const { postImg } = require('../model/postImg')
const { Topic } = require('../model/topics')
const fs = require('fs-extra')
const { getRootPath, rootPath,getUserLever,fetchAddress ,getMaterialSrc} = require('../utils')
const {User} = require('../model/user')
const {Level} = require("../model/level")
const config = require('../config')
const moment = require('moment-timezone');
//获取帖子列表
exports.getTopicList = async (req, res, next) => {
    try {
        //分页：获取当前页数
        let page = Math.max(req.query.page - 0, 1) - 1
        //设置每页条数
        const { per_page = 10 } = req.query
        let perpage = Math.max(req.query.per_page * 1, 1)
        let userVote = []
        let userCollect=[]
        if(req.loginuser){
            const loginuser = await User.findById(req.loginuser._id).select("+likingTopics +collectingTopics")
            userVote = loginuser.likingTopics
            userCollect = loginuser.collectingTopics
        }
        //设置关键词正则，i为不区分大小写
        let keyword = new RegExp(req.query.keyword,'i')
        let cate = new RegExp(req.query.cate,'i') 
        let topicsList = await Topic.find({
            $or:[
                {
                    title: {
                        $regex: keyword
                    }
                },
                {
                    text:{
                        $regex: keyword
                    }
                },
            ],
            cate:{
                $regex:cate
            }
        })
        .select("+status")
        .populate({
            path:"images user",
            select:"+experience",
            populate: {
                path:"avatar",
                strictPopulate:false
            }
        }).sort({createdAt :-1})
        if (!topicsList) return res.status(200).json({
            code: 400,
            msg: '获取帖子列表失败'
        })
        topicsList:await Promise.all(topicsList.map(async (item,index,array) => {
            if(item.status !=1){
                topicsList.splice(index,1)
            }
            if(item.user.experience){
                let levelNum= getUserLever(item.user.experience)
                let {level,url} =await Level.findOne({level:levelNum})
                item.user._doc["level"] = {
                    level:level,
                    url:url
                }
            } else {
                item.user._doc["level"] = {
                    level:'unknown',
                    url:`/level/level1.png`
                }
            }
            if(userVote.includes(item._id)){
                item._doc.isVote=true
            } else {
                item._doc.isVote=false
            }
            if(userCollect.includes(item._id )){
                item._doc.isCollected=true
            } else {
                item._doc.isCollected=false
            }

            return item
        }))
        res.status(200).json({
            code: 200,
            msg: '获取贴子列表成功',
            data: topicsList
        })
    } catch (err) {
        next(err)
    }
}

//帖子排序 时间降序，从最后到最新
exports.getTopicListbyTimeASC = async (req,res,next)=>{
    try {
        let userVote = []
        let userCollect=[]
        if(req.loginuser){
            const loginuser = await User.findById(req.loginuser._id).select("+likingTopics +collectingTopics")
            userVote = loginuser.likingTopics
            userCollect = loginuser.collectingTopics
        }
        //分页：获取当前页数
        let page = Math.max(req.query.page - 0, 1) - 1
        //设置每页条数
        const { per_page = 10 } = req.query
        let perpage = Math.max(req.query.per_page * 1, 1)
        let topicsList = await Topic.find({
            name: new RegExp(req.query.keyword) //模糊搜索
        })
        .select("+status")
        .populate({
            path:"images user",
            select:"+experience",
            populate: {
                path:"avatar",
                strictPopulate:false
            }
        }).sort({createdAt:1})
        if (!topicsList) return res.status(200).json({
            code: 400,
            msg: '获取帖子列表失败'
        })
        topicsList:await Promise.all(topicsList.map(async (item,index,array) => {
            if(item.status !=1){
                topicsList.splice(index,1)
            }
            if(item.user.experience){
                let levelNum= getUserLever(item.user.experience)
                let {level,url} =await Level.findOne({level:levelNum})
                item.user._doc["level"] = {
                    level:level,
                    url:url
                }
            } else {
                item.user._doc["level"] = {
                    level:'unknown',
                    url:`/level/level1.png`
                }
            }
            if(userVote.includes(item._id)){
                item._doc.isVote=true
            } else {
                item._doc.isVote=false
            }
            if(userCollect.includes(item._id )){
                item._doc.isCollected=true
            } else {
                item._doc.isCollected=false
            }
            return item
        }))
        res.status(200).json({
            code: 200,
            msg: '获取贴子列表成功',
            data: topicsList
        })
    } catch (err) {
        next(err)
    }
}
//根据点赞数量获取帖子
exports.getTopicListbypraise = async (req,res,next)=>{
    try {
        let userVote = []
        let userCollect=[]
        if(req.loginuser){
            const loginuser = await User.findById(req.loginuser._id).select("+likingTopics +collectingTopics")
            userVote = loginuser.likingTopics
            userCollect = loginuser.collectingTopics
        }
        //分页：获取当前页数
        let page = Math.max(req.query.page - 0, 1) - 1
        //设置每页条数
        const { per_page = 10 } = req.query
        let perpage = Math.max(req.query.per_page * 1, 1)
        let topicsList = await Topic.find({
            name: new RegExp(req.query.keyword) //模糊搜索
        })
        .select("+status")
        .populate({
            path:"images user",
            select:"+experience",
            populate: {
                path:"avatar",
                strictPopulate:false
            }
        }).sort({praise:-1})
        
        if (!topicsList) return res.status(200).json({
            code: 400,
            msg: '获取帖子列表失败'
        })
        topicsList:await Promise.all(topicsList.map(async (item,index,array) => {
            if(item.status !=1){
                topicsList.splice(index,1)
            }
            if(item.user.experience){
                let levelNum= getUserLever(item.user.experience)
                let {level,url} =await Level.findOne({level:levelNum})
                item.user._doc["level"] = {
                    level:level,
                    url:url
                }
            } else {
                item.user._doc["level"] = {
                    level:'unknown',
                    url:`/level/level1.png`
                }
            }
            if(userVote.includes(item._id)){
                item._doc.isVote=true
            } else {
                item._doc.isVote=false
            }
            if(userCollect.includes(item._id )){
                item._doc.isCollected=true
            } else {
                item._doc.isCollected=false
            }
            return item
        }))
        res.status(200).json({
            code: 200,
            msg: '获取贴子列表成功',
            data: topicsList
        })
    } catch (err) {
        next(err)
    }
}

//获取热门推荐
exports.getTopicListbyHot = async (req,res,next)=>{
    try {
        let userVote = []
        let userCollect=[]
        if(req.loginuser){
            const loginuser = await User.findById(req.loginuser._id).select("+likingTopics +collectingTopics")
            userVote = loginuser.likingTopics
            userCollect = loginuser.collectingTopics
        }
        //分页：获取当前页数
        let page = Math.max(req.query.page - 0, 1) - 1
        //设置每页条数
        const { per_page = 10 } = req.query
        let perpage = Math.max(req.query.per_page * 1, 1)
        let topicsList = await Topic.find({
            name: new RegExp(req.query.keyword) //模糊搜索
        })
        .select("+status")
        .populate({
            path:"images user",
            select:"+experience",
            populate: {
                path:"avatar",
                strictPopulate:false
            }
        }).sort({read:-1}).sort({comments:-1})
        
        if (!topicsList) return res.status(200).json({
            code: 400,
            msg: '获取帖子列表失败'
        })
        topicsList:await Promise.all(topicsList.map(async (item,index,array) => {
            if(item.status !=1){
                topicsList.splice(index,1)
            }
            if(item.user.experience){
                let levelNum= getUserLever(item.user.experience)
                let {level,url} =await Level.findOne({level:levelNum})
                item.user._doc["level"] = {
                    level:level,
                    url:url
                }
            } else {
                item.user._doc["level"] = {
                    level:'unknown',
                    url:`/level/level1.png`
                }
            }
            if(userVote.includes(item._id)){
                item._doc.isVote=true
            } else {
                item._doc.isVote=false
            }
            if(userCollect.includes(item._id )){
                item._doc.isCollected=true
            } else {
                item._doc.isCollected=false
            }
            return item
        }))
        res.status(200).json({
            code: 200,
            msg: '获取贴子列表成功',
            data: topicsList
        })
    } catch (err) {
        next(err)
    }
}
//获取指定帖子
exports.getTopic = async (req, res, next) => {
    try {
        const { fields = "" } = req.query
        //字段过滤
        // const selectFields = fields.split(';').filter(f => f).map(f => " +" + f).join("")
        const topic = await Topic.findById(req.params.id).select("+status").populate({
            path:"images user",
            select:"+experience",
            populate: {
                path:"avatar",
                strictPopulate:false
            }
        })
        if (!topic) return res.status(200).json({
            code: 400,
            msg: '帖子不存在'
        })
        if (topic.status!=1) return res.status(200).json({
            code: 400,
            msg: '帖子已被隐藏'
        })
        if(topic.user.experience){
            let levelNum= getUserLever(topic.user.experience)
            let {level,url} =await Level.findOne({level:levelNum})
            topic.user._doc["level"] = {
                level:level,
                url:url
            }
        } else {
            topic.user._doc["level"] = {
                level:'unknown',
                url:`/level/level1.png`
            }
        }
        let follower = await User.find({ following: topic.user._id })
        const fansList = []
        follower.forEach((item,index,array)=>{
            fansList.push(item._id)
        })
        topic.user._doc["fansList"] = fansList
        
        res.status(200).json({
            code: 200,
            msg: '获取帖子成功',
            data: topic
        })
    } catch (err) {
        next(err)
    }
}

//新增帖子
exports.createTopic = async (req, res, next) => {
    try {
        let imgArr = req.body.imgArr
        if (!imgArr || imgArr.length == 0) {
            let images = []
            let topic = new Topic({ ...req.body, user: req.userData._id, images: images, createdAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss') })
            await topic.save()
            await User.findByIdAndUpdate(req.userData._id, { $inc: { experience: +6 } })
            res.status(200).json({
                code: 200,
                msg: '帖子发布成功',
                data: topic
            })
        } else {
            let images = []
            let imageId = ''
            let returnImg = []
            const p = new Promise((resolve, reject) => {
                imgArr.forEach(async (item, index, arr) => {
                    let nameStr = item.replace(/^https?:\/\/[^\/]*/mg,'')
                    let uid = nameStr.split('/')[2]
                    let imgName = nameStr.split('/')[3]
                    //在已经上传的图片数据库中查询发布帖子时拥有的图片
                    //移动上传的图片
                    try{
                        fs.moveSync(`${rootPath}/public/uploads/${uid}/${imgName}`, `${rootPath}/public/uploads/${imgName}`)
                        console.log('success')
                    } catch(err){
                        return reject()
                    }
                    const restu = await postImg.findOne({ name: imgName })
                    //更改数据库中图片的url
                    postImg.findByIdAndUpdate(restu.id, { url: `/uploads/${imgName}` }, () => { })
                    images.push(restu._id)
                    returnImg.push(`/uploads/${restu.name}`)
                    if (arr.length==images.length) {
                        imageId = uid
                        resolve()
                    }
                });
            })

            p.then(async () => { 
                let content = req.body.content
                let a = new RegExp(`/${imageId}`,'g')
                req.body.content = content.replace(a, '')
                req.body.imgArr = returnImg
                const topic = new Topic({ 
                    ...req.body,
                    user: req.userData._id,
                    images: images,
                    createdAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss') 
                })

                await topic.save()
                await User.findByIdAndUpdate(req.userData._id, { $inc: { experience: +6 } })
                res.status(200).json({
                    code: 200,
                    msg: '帖子发布成功,经验+6',
                    data: topic
                })
                try{
                    fs.removeSync(`${rootPath}/public/uploads/${imageId}/`)
                    console.log('remove success')
                } catch(err){
                    console.error(err);
                }
            },()=>{
                return res.status(400).json({
                    code:400,
                    msg:'上传图片失败'
                })
            })
        }
    } catch (err) {
        next(err)
    }
}
//更新帖子
exports.updateTopic = async (req, res, next) => {
    try {
        //
        let imgArr = req.body.imgArr
        // console.log(imgArr)
        if (!imgArr || imgArr.length == 0) {
            //帖子的图片组
            let images = []
            //帖子ID
            let topicId = req.params.id
            var topic = await Topic.findById(topicId).select('+images +status')
            if (req.userData._id != topic.user){
                return res.status(400).json({
                    code:400,
                    msg:"编辑帖子失败，你不是该帖子的发布者"
                })
            }
            if(topic.status!=1){
                return res.status(400).json({
                    code:400,
                    msg:"编辑帖子失败，帖子已被隐藏"
                })
            }
            const data = await Topic.findByIdAndUpdate(topicId, {
                content:req.body.content,
                title:req.body.title,
                cate:req.body.cate,
                images: images,
                imgArr:imgArr,
                updatedAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss') 
            }).select("+updatedAt")
            let updatedTopic = await Topic.findById(topicId)
            if(!data) {
                return res.status(200).json({
                    code: 200,
                    msg: '编辑帖子失败1',
                    data: data
                })
            }
            res.status(200).json({
                code: 200,
                msg: '编辑帖子成功',
                data: updatedTopic
            })
        } else {
            let topicId = req.params.id
          
            let topic=await Topic.findById(topicId)
            if (req.userData._id != topic.user){
                return res.status(400).json({
                    code:400,
                    msg:"编辑帖子失败，你不是该帖子的发布者"
                })
            }
            //帖子图片组
            let images = []
            //存储图片ID
            let imageId = ''
            //返回的图片
            let returnImg = []
            const p = new Promise(async (resolve, reject) => {
                //前端发送图片循环
                await Promise.all(imgArr.map(async (item, index, arr) => {
                    //切割帖子图片的字符串获取信息 
                    let nameStr = item.replace(/^https?:\/\/[^\/]*/mg,'')
                    let uid=''
                    let imgName =''
                    if(nameStr.split('/').length==4){
                        uid = nameStr.split('/')[2]
                        imgName = nameStr.split('/')[3]
                        //移动上传的图片
                        try{
                            fs.moveSync(`${rootPath}/public/uploads/${uid}/${imgName}`, `${rootPath}/public/uploads/${imgName}`)
                            // console.log(`${rootPath}/public/uploads/${uid}/${imgName}`)
                        } catch(err){
                            console.log(err)
                        }
                        //更改数据库中图片的url
                        const restu = await postImg.findOne({name: imgName })
                        if (restu){
                            await postImg.findByIdAndUpdate(restu.id, { url: `/uploads/${imgName}` })
                            // postImg.findByIdAndUpdate(res.id, { topic: topic._id }, () => { })
                            images.push(restu._id)
                            returnImg.push(`/uploads/${restu.name}`)
                        } else {
                            return reject()
                        }
                    }
                    if(nameStr.split('/').length==3){
                        imgName = nameStr.split('/')[2]
                        const restu = await postImg.findOne({name: imgName })
                        if(restu){
                            await postImg.findByIdAndUpdate(restu._id, { url: `/uploads/${imgName}` })
                            // await postImg.findByIdAndUpdate(restu._id, { topic: topic._id })
                            images.push(restu._id)
                            returnImg.push(`/uploads/${restu.name}`)
                            uid=restu.user
                        }
                    }
                    if ( arr.length==images.length) {
                        imageId = uid
                        resolve()
                    }
                    return item
                }));
            })
            p.then(async () => { 
                let content = req.body.content
                if(imageId.length!=0){
                    let a = new RegExp(`/${imageId}`,'g')
                    req.body.content = content.replace(a, '')
                }
                req.body.imgArr = returnImg
                const data = await Topic.findByIdAndUpdate(topicId, {
                    content:req.body.content,
                    title:req.body.title,
                    cate:req.body.cate,
                    images: images,
                    imgArr:imgArr,
                    updatedAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss') 
                }).select("+updatedAt")
                if(!data){
                    return res.status(200).json({
                        code: 200,
                        msg: '编辑帖子失败2',
                        data: data
                    })
                }
                res.status(200).json({
                    code: 200,
                    msg: '编辑帖子成功',
                    data: topic
                })
            },()=>{ 
                return res.status(200).json({
                    code:400,
                    msg:"图片出错，请删除错误图片重新修改"
                })
            })
        }
    } catch (err) {
        next(err)
    }
}
//删除帖子
exports.deleteTopic = async (req, res, next) => {
    try {
        let user = req.userData._id
        const data = await Topic.findByIdAndRemove(req.params.id)
        if(data.user != user){
            return res.status(200).json({
                code: 400,
                msg: '删除帖子失败,请先登录',
            })
        }
        console.log(data)
        if (!data) return res.status(200).json({
            code: 400,
            msg: '删除帖子失败',
        })

        res.status(200).json({
            code: 200,
            msg: '删除帖子成功',
            data: data
        })
    } catch (err) {
        next(err)
    }
}
//获取指定用户帖子
exports.getUserTopic = async (req, res, next) => {
    try {
        const userId = req.params.id
        let topicList = await Topic.find({user:userId}).select("+status").populate('images').sort({createdAt:-1})
        if (!topicList) return res.status(200).json({
            code:400,
            msg:"获取用户帖子列表失败"
        })
        topicList.forEach((item,index) => {
            if(item.status !=1){
                topicList.splice(index,1)
            }
        })
        res.status(200).json({
            code:200,
            msg:"获取用户帖子列表成功",
            data:topicList
        })
    } catch (err) {
        next(err)
    }
}

//帖子浏览数+1
exports.readTopic = async (req, res, next) => {
    try{
        await Topic.findByIdAndUpdate(req.params.id, { $inc: { read: +1 } })
        res.status(200).json({
            code:200,
            msg:"操作成功"
        })
    } catch (err){
        next(err)
    }
}
